import axios from 'axios'
import utils from '../../modules/utils'


const defaultOptions = {
  baseURL: null,
  timeout: 300,
  headers: {},
  beforeRequest: function (config) {
    return config;
  },
  requestError: function (error) {
    return Promise.reject(error)
  },
  beforeResponse: function (response) {
    return response;
  },
  responseError: function (error) {
    return Promise.reject(error)
  }
}

/*
* 封装一个私有的请求方法
*/
const _request = (method, url, data, config) => {
  const configData = {
    url: url, // 请求的地址
    timeout: defaultOptions.timeout, // 超时时间, 单位毫秒
    headers: Object.assign({}, defaultOptions.headers)
  }
  if (!utils.isEmpty(defaultOptions.baseURL)) {
    configData["baseURL"] = defaultOptions.baseURL
  }
  if (method === 'get') {
    configData.method = 'get'
    configData.params = data// get 请求的数据
  } else if (method === 'postForm') {
    configData.method = 'POST'
    configData.headers['Content-Type'] = 'multipart/form-data; charset=UTF-8'
    if (data instanceof FormData) {
      configData.data = data
    } else {
      configData.data = utils.FormData.getFormData(data)
    }
  } else if (method === 'postJson') {
    configData.method = 'post'
    configData.headers['Content-Type'] = 'application/json; charset=UTF-8'
    configData.data = data
  }
  Object.assign(configData, config);
  return axios(configData)
}

class Ajax {
  get = function (url, data = {}, config = {}) {
    return _request('get', url, data, config)
  }
  postForm = function (url, data = {}, config = {}) {
    return _request('postForm', url, data, config)
  }

  postJson = function (url, data = {}, config = {}) {
    return _request('postJson', url, data, config)
  }
  // 默认post的Content-Type是application/json
  post = this.postJson
}

const AjaxPlugin = {
  install: function (Vue, options = defaultOptions) {
    console.log("plugin:bianmaba-ajax is loaded,mounted on (Vue.$ajax、Vue.ajax、Vue.$axios、Vue.axios)")
    Object.assign(defaultOptions, options)
    options = defaultOptions;
    axios.interceptors.request.use(options.beforeRequest, options.requestError)
    axios.interceptors.response.use(options.beforeResponse, options.responseError)
    Vue.prototype.$ajax = Vue.prototype.ajax = new Ajax();
    Vue.prototype.$axios = Vue.prototype.axios = axios;

    axios.interceptors.request.use(function (config) {
      config.url = config.url.startsWith("http://") ? config.url : (utils.isEmpty(options.baseURL) ? config.url : options.baseURL + config.url)
      return config
    }, function (error) {
      return Promise.reject(error)
    });


    axios.interceptors.response.use(
      response => {
        return response
      },
      error => {
        return Promise.reject(error)
      }
    )
  }
}
export const ajax = new Ajax();
export default AjaxPlugin

